//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect } from 'react';
import s from './index.module.less';
import { observer } from 'mobx-react';
import ReadDoc from './components/ReadDoc';
import WriteDoc from './components/WriteDoc';
import { useDocStores } from "./store";
import { useLocation } from 'react-router-dom';
import type * as NoticeType from '@/api/notice_type';
import { listen } from '@tauri-apps/api/event';
import { appWindow } from '@tauri-apps/api/window';

const ProjectDoc = () => {
  const store = useDocStores();

  const location = useLocation();
  const urlParams = new URLSearchParams(location.search);
  const projectId = urlParams.get("projectId") ?? "";
  const docId = urlParams.get("docId") ?? "";
  const inEditStr = urlParams.get("inEdit") ?? "false";

  useEffect(() => {
    store.projectId = projectId;
    store.docId = docId;
    store.loadProjectAndUser();
    store.loadDoc();
    appWindow.setAlwaysOnTop(true);
    setTimeout(() => {
      appWindow.setAlwaysOnTop(false);
    }, 500);
    store.inEdit = inEditStr.toLocaleLowerCase() == "true";
  }, []);

  useEffect(() => {
    appWindow.setClosable(!store.inEdit);
  }, [store.inEdit]);

  useEffect(() => {
    const unListenFn = listen<NoticeType.AllNotice>("notice", ev => {
      const notice = ev.payload;
      if (notice.ClientNotice?.WatchChangeNotice != undefined) {
        if (notice.ClientNotice.WatchChangeNotice.targetId == store.docId && !store.inEdit) {
          store.loadDoc();
        }
      } else if (notice.EntryNotice?.UpdateEntryNotice != undefined) {
        if (notice.EntryNotice.UpdateEntryNotice.entry_id == store.docId && !store.inEdit) {
          store.loadDoc();
        }
      } else if (notice.ProjectNotice?.UpdateProjectNotice != undefined && notice.ProjectNotice.UpdateProjectNotice.project_id == store.projectId) {
        store.loadProjectAndUser();
      } else if (notice.ProjectNotice?.UpdateMemberNotice != undefined && notice.ProjectNotice.UpdateMemberNotice.project_id == store.projectId && notice.ProjectNotice.UpdateMemberNotice.member_user_id == store.myUserId) {
        store.loadProjectAndUser();
      }
    });
    return () => {
      unListenFn.then((unListen) => unListen());
    };
  }, []);

  return (
    <>
      {store.project != null && store.doc != null && (
        <div className={s.doc_wrap}>
          {store.inEdit && <WriteDoc />}
          {!store.inEdit && <ReadDoc />}
        </div>
      )}
    </>
  );
};

export default observer(ProjectDoc);
